<?php
//数组中的健值要和id相同
$arr = array(
	1 => array('id' => 1, 'pid' => 0, 'name' => '中国'),
	2 => array('id' => 2, 'pid' => 1, 'name' => '湖北省'),
	3 => array('id' => 3, 'pid' => 1, 'name' => '上海'),
	4 => array('id' => 4, 'pid' => 2, 'name' => '武汉市'),
	5 => array('id' => 5, 'pid' => 2, 'name' => '仙桃市'),
	6 => array('id' => 6, 'pid' => 4, 'name' => '江汉区'),
	7 => array('id' => 7, 'pid' => 4, 'name' => '新洲区'),
	8 => array('id' => 8, 'pid' => 3, 'name' => '闵行区'),
	9 => array('id' => 9, 'pid' => 3, 'name' => '浦东区'),
	10=> array('id' => 10,'pid' => 7, 'name' => '邾城街'),
	11=> array('id' => 11,'pid' => 0, 'name' => '美国'),
	12=> array('id' => 12,'pid' =>11, 'name' => '纽约')
);

//echo "<pre>";
//print_r($arr);
//echo "</pre>";

//查看数组被改变的过程
function get_tree2($arr){
	foreach($arr as $v){
		$arr[$v['pid']]['son'][] = &$arr[$v['id']];
		$i++;
		echo $i;
		echo "<hr>";
		echo "<pre>";
		print_r($arr);
		echo "</pre>";
	}
}

//上面的方法是网络里面找的，下面这个方法是自己写的
function get_tree($arr){
	foreach($arr as $v){
		$arr[$v['pid']]['children'][]= &$arr[$v['id']];
	}
//	return $arr[0]['children'];
	return $arr[0];
}

//get_tree2($arr);

$arr_tree = get_tree($arr);
$arr_tree['name'] = '世界';
echo "<pre>";
print_r($arr_tree);
echo "</pre>";

$json = json_encode($arr_tree);
var_dump($json);


?>
<html>
<head>
	<meta charset="UTF-8">
	<title>get_tree</title>
	<script src="study/d3/d3.v3.min.js" charset="utf-8"></script>
	<style>
		svg{width: 1200px;height: 800px;display: block;}
		/*svg{width: 10000px;height: 10000px;display: block;}*/
		path.link{stroke: #aaa;stroke-width: 1.5px;fill:transparent;}
		.node circle{fill:#fff;stroke:steelblue;stroke-width: 1.5px;}
	</style>
</head>
<body>
<svg></svg>	
</body>
<script type="text/javascript">


var tree = d3.layout.tree()
			.size([600, 500])
//			.size([3000, 1500])
			.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2); });
d3.json("diy.json", function(error, root) {
	var root2 = '<?php echo $json;?>';
	var root3 = JSON.parse(root2);
	console.log(root3);
	var nodes = tree.nodes(root3);
	var links = tree.links(nodes);
//	console.log(nodes);
//	console.log(links);
//console.log(root3);
	var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });
	var svg = d3.select('svg').append('g').attr("transform", "translate(50,0)");
	var link = svg.selectAll(".link").data(links).enter().append("path").attr("class", "link").attr("d", diagonal);
	var node = svg.selectAll('.node').data(nodes).enter().append('g').attr('class','node').attr('transform',function (d) {return "translate(" + d.y + "," + d.x + ")";});
	node.append('circle').attr('r',5);
	node.append('text').attr("dx", function(d) { return d.children ? -8 : 8; }).attr("dy", 3).style("text-anchor", function(d) { return d.children ? "end" : "start"; })
		.append("a").attr('href',"https://www.baidu.com/").text(function(d) { return d.name; });
})


</script>
</html>

